<?php

/**
 * This file is part of workerman.
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the MIT-LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @author walkor<walkor@workerman.net>
 * @copyright walkor<walkor@workerman.net>
 * @link http://www.workerman.net/
 * @license http://www.opensource.org/licenses/mit-license.php MIT License
 */

/**
 * 用于检测业务代码死循环或者长时间阻塞等问题
 * 如果发现业务卡死，可以将下面declare打开（去掉//注释），并执行php start.php reload
 * 然后观察一段时间workerman.log看是否有process_timeout异常
 */
//declare(ticks=1);

use \GatewayWorker\Lib\Gateway;

/**
 * 主逻辑
 * 主要是处理 onConnect onMessage onClose 三个方法
 * onConnect 和 onClose 如果不需要可以不用实现并删除
 */
class Events
{
    /**
     * 当客户端连接时触发
     * 如果业务不需此回调可以删除onConnect
     * 
     * @param int $client_id 连接id
     */
    public static function onConnect($client_id)
    {
        // 向当前client_id发送数据 
        // Gateway::sendToClient($client_id, "Hello $client_id\r\n");
        // 向所有人发送
        // Gateway::sendToAll("$client_id login\r\n");

        // 给前端返回,绑定用户与client_id
        Gateway::sendToClient($client_id, self::encodeMsg('bind', 1, 'ok', [
            'client_id' => $client_id,
        ]));
    }

    /**
     * 当客户端发来消息时触发
     * @param int $client_id 连接id
     * @param mixed $message 具体消息
     */
    public static function onMessage($client_id, $message)
    {
        // 向所有人发送 
        // Gateway::sendToAll("$client_id said $message\r\n");

        echo $message . PHP_EOL;
        if (!$message) {
            // 可能是心跳检测
            return;
        }

        $data = self::decodeMsg($message);
        $data['client_id'] = $client_id;

        // 加入房间放到duadmin了
        if (false && $data['type'] == 'joinGroup') {
            // 加入房间
            Gateway::joinGroup($client_id, $data['group_id']);

            $groups = Gateway::getClientSessionsByGroup($data['group_id']);
            // 单机调试
            if (count($groups) == 1) {
                // 匹配成功，分配红蓝方
                $arr = [
                    0 => 'red',
                    1 => 'blue',
                ];
                $i = 0;
                foreach ($groups as $cur_client_id => $group) {
                    Gateway::sendToClient($cur_client_id, self::encodeMsg('setRole', 1, 'ok', [
                        'role' => $arr[$i],
                    ]));
                    $i++;
                }
            }
            return;
        }

        $group_id = self::makeGroupIdByRoomId($data['group_id']);
        // 转发前端消息
        Gateway::sendToGroup($group_id, self::encodeMsg($data['type'], 1, 'ok', $data['data']));
    }

    /**
     * 当用户断开连接时触发
     * @param int $client_id 连接id
     */
    public static function onClose($client_id)
    {
        // 向所有人发送 
        // GateWay::sendToAll("$client_id logout\r\n");

        GateWay::sendToAll(self::encodeMsg('close', 1, 'ok', [
            'client_id' => $client_id,
        ]));
    }

    private static function encodeMsg($type, $code, $msg, $data = [])
    {
        return json_encode([
            'type' => $type,
            'code' => $code,
            'msg' => $msg,
            'data' => $data,
        ], JSON_UNESCAPED_UNICODE);
    }

    private static function decodeMsg($msg)
    {
        if (!$msg) {
            return [];
        }
        return json_decode($msg, true);
    }

    /**
     * 生成socket群id
     */
    private static function makeGroupIdByRoomId($roomId)
    {
        return "tetris-room-{$roomId}";
    }
}
